package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.CartListRedis;
import com.dongdongshop.data.HttpResponseEnum;
import com.dongdongshop.data.Result;
import com.dongdongshop.pojo.Cart;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.CartServiceI;
import com.dongdongshop.service.ItemServiceI;
import com.dongdongshop.util.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("cart")
public class CartController {

    private final Logger logger= LoggerFactory.getLogger(CartController.class);
    @Reference
    private CartServiceI cartServiceI;
    @Reference
    private ItemServiceI itemServiceI;

    //跳转购物车页面
    @RequestMapping("addCart")
    public String addCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num, Model model){
        setCart(request,response,itemId,num);
        TbItem item =itemServiceI.selectItemById(itemId);
        model.addAttribute("item",item);
        model.addAttribute("num",num);
        return "success-cart";
    }

    @RequestMapping("toCart")
    public String toCart(){
        return "cart";
    }

    //获取购物车
    @RequestMapping("getCart1")
    @ResponseBody
    public Result getCart1(HttpServletRequest request,HttpServletResponse response){
        try {
            List<Cart> cart = getCart(request, response);
            return Result.jsonResponse(HttpResponseEnum.OK).setData(cart);
        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
    }



    /*
    前台页面不登录，商品加入购物车后 能看到加入购物车
    获取购物车
    */
    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request, HttpServletResponse response){
        //判断用户是否登录
        TbUser user =(TbUser) SecurityUtils.getSubject().getPrincipal();
        //从cookie这个中获取购物车信息
        String cartListstr = CookieUtils.getCookieValue(request, CartListRedis.CARTLIST, "UTF-8");
        //判断购物车如果为空，我们防止空指针
        if (StringUtils.isBlank(cartListstr)){
            cartListstr="[]";//防止报空指针
        }
        //将字符串转成List集合
        List<Cart> cartList = JSONObject.parseArray(cartListstr, Cart.class);
        if (user == null){//1.没登录查询cookie
            return cartList;
        }else {//2.登录走redis
            //从redis中查询出购物车列表
            List<Cart> cartListFromRedis = cartServiceI.getCartListFromRedis(user.getUsername());
            //判断cookie中是否有数据
            if (cartList.size()>0){//有数据就添加到redis中，反之不添加
                //合并购物车
                cartListFromRedis= cartServiceI.mergeCookieAndRedis(cartList,cartListFromRedis);
                //将合并得购物车，存放到redis
                cartServiceI.saveCartListToRedis(user.getUsername(),cartListFromRedis);
                //清楚cookie中得购物车
                CookieUtils.deleteCookie(request,response,CartListRedis.CARTLIST);
            }
            return cartListFromRedis;
        }
    }

    //享购物车内添加数据
    @RequestMapping("setCart")
    @ResponseBody
    public Result setCart(HttpServletRequest request, HttpServletResponse response,Long itemId,Integer num){
        //判断用户是否登录 1.没登录查询cookie 2.登录走redis
        TbUser user=(TbUser)SecurityUtils.getSubject().getPrincipal();
        //先从cookie中获取购物车的数据  直接调用上面getCart()方法
        List<Cart> cartList = getCart(request, response);
        //调用dubbo组装购物车  cartList原来的购物车数据 增加时需要商品的id和数量num
        try {
            //调用购物车服务 增加购物车
            cartList=cartServiceI.addCartList(cartList,itemId,num);//增加之后覆盖原来(上面)的cartList
            if (user == null){
                CookieUtils.setCookie(request,response,CartListRedis.CARTLIST,JSONObject.toJSONString(cartList),24*60*60,"UTF-8");
            }else {
                cartServiceI.saveCartListToRedis(user.getUsername(),cartList);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.jsonResponse(HttpResponseEnum.FAIL);
        }
        System.out.println("添加方法");
        return Result.jsonResponse(HttpResponseEnum.OK);
    }
}
